package test.san.baseproject.base

/*

具有上拉加载下拉刷新的Fragment

公共HomeView
adapter
presenter

 */


import android.view.View
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import kotlinx.android.synthetic.main.fragment_home.*
import test.san.baseproject.R

abstract class BaseListFragment<RESPONSE, ITEMBEAN, ITEMVIEW: View>: BaseFragmnet(), BaseView<RESPONSE> {

    override fun onError(message: String?) {
        Toast.makeText(context, "获取数据失败", Toast.LENGTH_SHORT)
    }

    override fun loadSuccess(bean: RESPONSE?) {
        refresh.isRefreshing = false
        baseAdapter.updateList(getList(bean))
    }

    override fun loadMore(bean: RESPONSE?) {
        refresh.isRefreshing = false
        baseAdapter.moreList(getList(bean))
    }

    // 从返回结果中获取数据列表结合
    abstract fun getList(bean: RESPONSE?): List<ITEMBEAN>

    val baseAdapter by lazy { getSpecialAdapter() }

    // 获取adapter
    abstract fun getSpecialAdapter(): BaseListAdapter<ITEMBEAN, ITEMVIEW>

    val presneter by lazy { getSpecialPresenter() }

    // 获取presenter
    abstract fun getSpecialPresenter(): BaseListPresenter

    override fun initView(): View? {
        val view = View.inflate(context, R.layout.fragment_home, null)
        return view
    }


    override fun initLister() {
        home_recycle.layoutManager = LinearLayoutManager(context)
        home_recycle.adapter = baseAdapter

        // 刷新
        refresh.setOnRefreshListener {
            presneter.loadDatas()
        }

        home_recycle.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                if (newState == RecyclerView.SCROLL_STATE_IDLE) { // 空闲状态
                    // 判断是否是最后一条
                    val layoutManager = recyclerView.layoutManager
                    if (layoutManager is LinearLayoutManager) {
                        val manager = layoutManager
                        val lastPosition = manager.findLastVisibleItemPosition()
                        if (lastPosition == baseAdapter.itemCount - 1) { // 最后一条
                            presneter.loadMore()
                        }
                    }

                }
            }
        })
    }

    override fun initData() {
//        loadDatas()

        // 修改成 mvp
        presneter.loadDatas()
    }
}